package project1task4re;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Steven Suit
 * COSC 603
 * Project 1 Task 4
 * 
 */
public class stutter {

	// Global variables
	private static String[] split;
	private static String line;
	private static String lastWord;
	
	/**
	 * Check for file passed in as argument,
	 * if not, use keyboard input
	 * 
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException  {
		BufferedReader br = null;
		if (args.length == 0)
			findStutter(new BufferedReader(new InputStreamReader(System.in)));
		else
			while (args.length > 0) {				
				br = new BufferedReader(new FileReader(args[0]));
				findStutter(br);
				br.close();
				break;
			}
	}

	/**
	 * From the file passed in, check for duplicate words
	 * 
	 * @param input
	 * @throws IOException
	 */
	public static void findStutter(BufferedReader input) throws IOException {
		line = new String();
		int count = 1;
		
		while ((line = input.readLine()) != null) {
			String delimiter = "[ .,!?:;(\"-]+\\s*";
			split = line.split(delimiter);
			
			for (int i = 0; i < split.length; i++) {
				if (i+1 > split.length - 1) {
					lastWord = split[i];
					break;
				}
				
				if (compareWords(split[i], split[i+1]))
					printStutter(count, split[i], split[i+1]);
				
				if (lastWord != null)
					if (compareWords(lastWord, split[i])) 
						printStutter(count, lastWord, split[i]);				
			}
			count++;
		}
		System.out.println();
	}
	
	/**
	 * Compare _word1 to _word2
	 * 
	 * @param _word1
	 * @param _word2
	 * @return true if equal
	 */
	public static boolean compareWords(String _word1, String _word2) {
		return (_word1.equals(_word2) ? true : false);
	}
	
	/**
	 * Print line in which stutter was found and the duplicate word
	 * @param _line
	 * @param _word1
	 * @param _word2
	 */
	public static void printStutter(int _line, String _word1, String _word2) {
		System.out.printf("Repeated word on line %d: %s %s\n", _line, _word1, _word2);
	}
}
